package ac.svn.accesscontrol.controller;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JTextPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import ac.svn.accesscontrol.manager.SVNInfoManager;
import ac.svn.accesscontrol.store.AccessUnit;
import ac.svn.accesscontrol.store.IResources;
import ac.svn.accesscontrol.store.ISVNItem;
import ac.svn.accesscontrol.store.SVNGroup;
import ac.svn.accesscontrol.store.SVNLocation;
import ac.svn.accesscontrol.store.SVNTag;
import ac.svn.accesscontrol.ui.IUIConstants;
import ac.svn.accesscontrol.ui.UIComponentLibrary;
import ac.svn.accesscontrol.ui.window.TagEditorWindow;
import ac.svn.accesscontrol.utils.Utility;

public class TagEditorController {

	private JMenuItem	miShowTagEditor;
	private TagEditorWindow  editorWindow;


	public TagEditorController()
	{
		editorWindow = new TagEditorWindow();
		UIComponentLibrary.addComponent(IUIConstants.C_TAG_EDITOR, editorWindow);

		miShowTagEditor = new JMenuItem("Tag Editor");
		miShowTagEditor.setIcon(Utility.getImageIcon(IResources.LOC_ICN_TAG_SMALL));
		miShowTagEditor.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent ae) {
				editorWindow.showTagEditor();				
			}
		});

		JMenu toolsMenu = (JMenu) UIComponentLibrary.getComponent(IUIConstants.M_TOOL_MENU);
		if(null != toolsMenu)
		{
			toolsMenu.add(miShowTagEditor);
		}

		registerListener();
	}

	private void registerListener() {
		if(null != editorWindow)		
		{
			if(null != editorWindow.getTagsListView())
			{
				editorWindow.getTagsListView().addListSelectionListener(new ListSelectionListener() {
					@Override
					public void valueChanged(ListSelectionEvent lse) {
						//Check if event is not generated  on un-selection event.
						if(false == lse.getValueIsAdjusting())
						{
							//get Selected value
							SVNTag svnTag = (SVNTag) editorWindow.getTagsListView().getSelectedValue();
							//If any value is selected.
							if(null != svnTag)
							{
								if(null != editorWindow.getTextPane())
								{
									editorWindow.getTextPane().showTag(svnTag);
								}
								else
								{
									System.err.println("TextEditor in TagEditorWindow in not initialized.");
								}
							}
						}
					}
				});
			}
			else
			{
				System.err.println("List in TagEditor Window in not initialized.");
			}


			editorWindow.getMIGenerateTags().addActionListener(new ActionListener() 
			{
				@Override
				public void actionPerformed(ActionEvent arg0) {
					editorWindow.getTextPane().setText("");
					generateTags();
				}
			});

		}
	}

	public void generateTags()
	{
		Thread listerThread = new Thread(new Runnable() 
		{
			@Override
			public void run() {
				JTextPane textPane = editorWindow.getTextPane();
				textPane.setText(generateContents()); 
			}
		});

		listerThread.start();
	}

	private String generateContents()
	{
		//Get SVNInformanager.
		SVNInfoManager  svnInfMgr = SVNInfoManager.getInfoManager();

		//Buffer for final file
		StringBuffer stringBuffer = new StringBuffer();

		//Generate contents.
		stringBuffer.append("#Generated on " + (new Date()).toString() + "\n");
		stringBuffer.append("[groups]\n");

		List<SVNGroup> allGroups = new ArrayList<SVNGroup>();
		
		for(ISVNItem item : svnInfMgr.getAllGroups())
		{
			SVNGroup  svnGroup = (SVNGroup) item;
			allGroups.add(svnGroup);
		}
		 
		//Sort By group name
		Collections	.sort(allGroups);
		
		for(SVNGroup svnGroup : allGroups)
		{
			String groupTag = "";

			String header = svnGroup.getComments();			
			String userList = svnGroup.getGroupMembers().toString();
			userList = userList.replace("["," ");
			userList = userList.replace("]"," ");
			userList = userList.trim();


			if((null != header) && (false == header.trim().isEmpty()))
			{
				groupTag = String.format("\n%s%s=%s\n",header,svnGroup.getGroupName(),userList);
			}
			else
			{
				groupTag = String.format("%s=%s\n",svnGroup.getGroupName(),userList);
			}
			stringBuffer.append(groupTag);
		}

		stringBuffer.append("\n\n");

		for(ISVNItem item : svnInfMgr.getAllLocations())
		{
			SVNLocation svnLocation = (SVNLocation) item;
			String locationHeader = svnLocation.getComments();
			
			if(null == locationHeader)
			{
				locationHeader = "";
			}
			
			StringBuffer locationTag = new StringBuffer(String.format("%s[%s]\n",locationHeader,svnLocation.getLocationPath()));
			for(String  accessUnitId : svnLocation.getAccessUnits())
			{
				AccessUnit accessUnit = svnInfMgr.getAccessUnit(accessUnitId);
				String header = accessUnit.getComments();

				if(null == header)
				{
					header = "";
				}
		
				String prefix = "";
				if(svnInfMgr.isAGroup(accessUnit.getOwnerId()))
				{
					prefix = "@";
				}

				String strAccessUnit = String.format("%s%s%s = %s\n",header,prefix,accessUnit.getOwnerId(),accessUnit.getAccessAsString());
				locationTag.append(strAccessUnit);									
			}
			stringBuffer.append(locationTag + "\n");
		}

		return stringBuffer.toString();
	}

}
